package ChatNI;

import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class InetAdressSearcher {

	/**
	 * @throws UnknownHostException
	 * @throws SocketException
	 * @return LocalIp
	 */
	public static String getLocalIP() throws UnknownHostException, SocketException {
		Enumeration en = NetworkInterface.getNetworkInterfaces();
		String ip ="";
		boolean premierIp= false;
		while (en.hasMoreElements()) {
			NetworkInterface ni = (NetworkInterface) en.nextElement();
			Enumeration ee = ni.getInetAddresses();
			while (ee.hasMoreElements()) {
				while (ee.hasMoreElements()) {
					InetAddress ia = (InetAddress) ee.nextElement();
					if (!ia.isLoopbackAddress() & !ia.isLinkLocalAddress() & !premierIp) {
						premierIp=true;
						System.out.println(ia.getHostAddress());
						ip = ia.getHostAddress();
					}
				}
			}
		}
		return ip ;
	}


	/**
	 * @param args
	 * @throws SocketException
	 * @return Local Broadcast Ip
	 */
	public static InetAddress getLocalBroadcastIp() throws SocketException {
		InetAddress broadcast = null;
		Enumeration<NetworkInterface> interfaces =
				NetworkInterface.getNetworkInterfaces();
		while (interfaces.hasMoreElements()) {
			NetworkInterface networkInterface = interfaces.nextElement();
			if (networkInterface.isLoopback())
				continue;    // Don't want to broadcast to the loopback interface
			for (InterfaceAddress interfaceAddress :
				networkInterface.getInterfaceAddresses()) {
				broadcast = interfaceAddress.getBroadcast();
				if (broadcast == null)
					continue;
				else
					return broadcast;
				// Use the address
			}
		}
		return broadcast;
	}
}
